package top.mcwebsite.playandroid.business.gongzhonghao.impl.ui

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import kotlin.math.roundToInt
import top.mcwebsite.lib.route.api.EasyRouter
import top.mcwebsite.playandroid.business.gongzhonghao.impl.model.ChapterModel
import top.mcwebsite.playandroid.business.gongzhonghao.impl.vm.GongZhongHaoIntent
import top.mcwebsite.playandroid.business.gongzhonghao.impl.vm.GongZhongHaoUiEffect
import top.mcwebsite.playandroid.business.gongzhonghao.impl.vm.GongZhongHaoViewModel
import top.mcwebsite.playandroid.common.constant.RouteConfig.ArticleDetail
import top.mcwebsite.playandroid.common.uiWidget.skeleton
import top.mcwebsite.playandroid.lib.common.ext.encodeURL
import top.mcwebsite.playandroid.lib.mvi.model.Async

@Composable
fun GongZhongHaoPage() {
    val viewModel: GongZhongHaoViewModel = viewModel()
    val uiState by viewModel.uiStateFlow.collectAsState()
    viewModel.HandleUiEffect {
        when (it) {
            is GongZhongHaoUiEffect.NavigationToArticleDetailPageUiEffect -> {
                EasyRouter.navigate(ArticleDetail.PATH + "/${it.articleModel.link.encodeURL()}")
            }
        }
    }
    Column {
        GongZhongHaoItems(gongZhongHaoItems = uiState.gongZhongHaoItems, selected = uiState.selectedItem) {
            viewModel.sendIntent(GongZhongHaoIntent.ClickTabItemIntent(it))
        }
        GongZhongHaoContent(
            selected = uiState.selectedItem,
            gongZhongHaoItems = uiState.gongZhongHaoItems,
            getPagerFlow = { viewModel.getPageFlow(it) },
            sendIntent = viewModel::sendIntent
        )
    }
}

@Composable
private fun GongZhongHaoItems(
    gongZhongHaoItems: Async<List<ChapterModel>>,
    selected: Int,
    onItemClick: (Int) -> Unit
) {
    when (gongZhongHaoItems) {
        is Async.Loading -> {
            GongZhongHaoItemsLoading()
        }

        is Async.Failed -> {
            // TODO
        }

        is Async.Success -> {
            GongZhongHaoItems(gongZhongHaoItems = gongZhongHaoItems.data, selected = selected, onItemClick)
        }

        Async.UnInitialization -> {

        }
    }
}

@Composable
fun GongZhongHaoItems(
    gongZhongHaoItems: List<ChapterModel>,
    selected: Int,
    onItemClick: (Int) -> Unit
) {
    val lazyRowState = rememberLazyListState()
    LaunchedEffect(selected) {
        val isVisible = lazyRowState.layoutInfo.visibleItemsInfo.find { it.index == selected } != null
        if (!isVisible) {
            lazyRowState.scrollToItem(selected, -500)
        }
    }
    // TODO Change To ScrollTabRow
    LazyRow(
        state = lazyRowState,
        modifier = Modifier.padding(vertical = 5.dp)
    ) {
        items(gongZhongHaoItems.size) { index ->
            Box(
                modifier = Modifier
                    .padding(
                        start = if (index == 0) 10.dp else 6.dp,
                        end = if (index == gongZhongHaoItems.size - 1) 10.dp else 6.dp
                    )
                    .clip(RoundedCornerShape(25.dp))
                    .clickable(
                        indication = rememberRipple(),
                        interactionSource = remember { MutableInteractionSource() },
                    ) {
                        onItemClick(index)
                    }
                    .background(
                        color = if (index == selected) {
                            MaterialTheme.colorScheme.primary
                        } else {
                            MaterialTheme.colorScheme.surfaceVariant
                        }, shape = RoundedCornerShape(25.dp)
                    )
            ) {
                Text(
                    text = gongZhongHaoItems[index].name,
                    modifier = Modifier.padding(horizontal = 12.dp, vertical = 5.dp),
                    style = MaterialTheme.typography.labelMedium
                )
            }
        }
    }
}

@Composable
fun GongZhongHaoItemsLoading() {
    BoxWithConstraints(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 5.dp)
    ) {
        // 计算能放多少个，宽度 50dp
        val itemCount = ((this.maxWidth - 4.dp) / 62.dp).roundToInt()
        Row {
            repeat(itemCount) {
                Box(
                    modifier = Modifier
                        .padding(start = if (it == 0) 10.dp else 6.dp, end = 6.dp)
                        .width(50.dp)
                        .skeleton(true)
                ) {
                    Text(
                        text = "占",
                        modifier = Modifier.padding(horizontal = 12.dp, vertical = 5.dp),
                        style = MaterialTheme.typography.labelMedium
                    )
                }
            }
        }
    }
}